package org.spring.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.springboot.domain.Category;
import org.spring.springboot.service.CategoryService;
import org.spring.springboot.util.MessageUtils;
import org.spring.springboot.vo.CategoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;

/**
 * 分类 Controller 实现 Restful HTTP 服务
 * <p>
 * Created by 赵新国 on 07/02/2017.
 */
@RestController
@RequestMapping("/admin")
public class CategoryController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CategoryService categoryService;

    /**
     * 后台用户管理
     *
     * @return
     */
    @RequestMapping(value = "/category")
    public ModelAndView category() {
        return new ModelAndView("admin/category/categoryList");
    }

    @GetMapping(value = "/getCategoryList")
    public PageInfo<Category> getCategoryList(@RequestParam Integer pageNumber, @RequestParam Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List<Category> categoryList = categoryService.findAllCategory();
        logger.info("分类列表：" + categoryList.toString());
        return new PageInfo<Category>(categoryList);
    }

    @PostMapping(value = "/saveCategory")
    public HashMap<String, Object> saveCategory(Model model, CategoryVo categoryVo) {
        HashMap<String, Object> retMap = MessageUtils.success();
        try {
            Category category = new Category();
            BeanUtils.copyProperties(categoryVo, category);
            categoryService.saveCategory(category);
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 管理分类信息页面
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/categoryForm")
    public ModelAndView categoryForm(@RequestParam(required = false) Integer id) {
        ModelAndView mav = new ModelAndView("/admin/category/categoryForm");
        Category category = new Category();
        if (id != null) {
            category = categoryService.findCategory(id);
        }
        List<Category> categoryList = categoryService.findAllCategory();
        mav.addObject("categoryList", categoryList);
        // 递归算法解析成树形结构
        Category category1 = categoryService.getTreeNodes(1);
        mav.addObject("category1", category1);
        logger.info("分类树：" + JSON.toJSONString(category1));
        mav.addObject("category", category);
        return mav;
    }

}
